<template>
  <div class="orders-page bg-gray-50 dark:bg-gray-900 min-h-screen p-6">
    <!-- 统计卡片 -->
    <a-row :gutter="16" class="mb-4">
      <a-col :span="6" v-for="stat in orderStats" :key="stat.title">
        <a-card class="stat-card dark:bg-gray-800" :loading="loading">
          <div class="stat-content">
            <div class="stat-title dark:text-gray-300">{{ stat.title }}</div>
            <div class="stat-value dark:text-white">{{ stat.value }}</div>
            <div class="stat-compare dark:text-gray-400">
              较昨日
              <span
                :class="[
                  stat.trend >= 0 ? 'trend-up' : 'trend-down',
                  'dark:text-green-400 dark:text-red-400',
                ]"
              >
                {{ stat.trend >= 0 ? "+" : "" }}{{ stat.trend }}%
                <icon-up v-if="stat.trend >= 0" />
                <icon-down v-else />
              </span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 搜索区域 -->
    <a-card class="search-card dark:bg-gray-800" :bordered="false">
      <a-form :model="searchForm" layout="inline">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item field="keyword" label="订单搜索">
              <a-input
                v-model="searchForm.keyword"
                placeholder="订单号/房间号/客人姓名"
                allow-clear
              >
                <template #prefix>
                  <icon-search />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="status" label="订单状态">
              <a-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                allow-clear
              >
                <a-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :value="item.value"
                >
                  <template #icon>
                    <div
                      class="status-dot"
                      :style="{ backgroundColor: getStatusColor(item.value) }"
                    ></div>
                  </template>
                  {{ item.label }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="dateRange" label="入住时间">
              <a-range-picker
                v-model="searchForm.dateRange"
                style="width: 100%"
                :shortcuts="dateShortcuts"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="roomType" label="房间类型">
              <a-select
                v-model="searchForm.roomType"
                placeholder="请选择房型"
                allow-clear
              >
                <a-option
                  v-for="type in roomTypes"
                  :key="type.id"
                  :value="type.id"
                >
                  {{ type.name }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon><icon-search /></template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon><icon-refresh /></template>
                重置
              </a-button>
              <a-button type="text" @click="showAdvanced = !showAdvanced">
                {{ showAdvanced ? "收起" : "展开" }}
                <icon-up v-if="showAdvanced" />
                <icon-down v-else />
              </a-button>
            </a-space>
          </a-col>
        </a-row>

        <!-- 高级搜索 -->
        <div v-show="showAdvanced" class="advanced-search mt-4">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item field="paymentMethod" label="支付方式">
                <a-select
                  v-model="searchForm.paymentMethod"
                  placeholder="请选择支付方式"
                  allow-clear
                >
                  <a-option value="wechat">微信支付</a-option>
                  <a-option value="alipay">支付宝</a-option>
                  <a-option value="unionpay">银联支付</a-option>
                  <a-option value="cash">现金支付</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="amount" label="订单金额">
                <a-input-number-range
                  v-model="searchForm.amount"
                  placeholder="最小金额 - 最大金额"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="source" label="预订来源">
                <a-select
                  v-model="searchForm.source"
                  placeholder="请选择来源"
                  allow-clear
                >
                  <a-option value="website">官网</a-option>
                  <a-option value="mobile">手机端</a-option>
                  <a-option value="ota">OTA平台</a-option>
                  <a-option value="walk_in">门店直订</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="tags" label="订单标签">
                <a-select
                  v-model="searchForm.tags"
                  placeholder="请选择标签"
                  allow-clear
                  multiple
                >
                  <a-option value="vip">VIP客人</a-option>
                  <a-option value="long_stay">长住</a-option>
                  <a-option value="group">团队</a-option>
                  <a-option value="special">特殊要求</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </a-card>

    <!-- 订单列表 -->
    <a-card class="list-card mt-4 dark:bg-gray-800" :bordered="false">
      <!-- 工具栏 -->
      <template #title>
        <div class="toolbar">
          <div class="left">
            <a-space>
              <a-button
                type="primary"
                status="success"
                :disabled="!selectedOrders.length"
                @click="handleBatchCheckIn"
              >
                <template #icon><icon-check-circle /></template>
                批量入住
              </a-button>
              <a-button
                type="primary"
                status="warning"
                :disabled="!selectedOrders.length"
                @click="handleBatchCheckOut"
              >
                <template #icon><icon-export /></template>
                批量退房
              </a-button>
              <a-button type="primary" @click="handleExport">
                <template #icon><icon-download /></template>
                导出订单
              </a-button>
            </a-space>
          </div>
          <div class="right">
            <a-space>
              <a-button
                type="text"
                @click="handleRefresh"
                class="dark:text-gray-300"
              >
                <template #icon><icon-refresh /></template>
                刷新
              </a-button>
              <a-button
                type="text"
                @click="handleColumnSetting"
                class="dark:text-gray-300"
              >
                <template #icon><icon-settings /></template>
                列设置
              </a-button>
              <a-dropdown @select="handleTableSize">
                <a-button type="text" class="dark:text-gray-300">
                  <template #icon><icon-list /></template>
                  密度
                </a-button>
                <template #content>
                  <a-doption value="large">宽松</a-doption>
                  <a-doption value="medium">中等</a-doption>
                  <a-doption value="small">紧凑</a-doption>
                </template>
              </a-dropdown>
            </a-space>
          </div>
        </div>
      </template>

      <!-- 订单表格 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :pagination="pagination"
        :loading="loading"
        :row-selection="rowSelection"
        :size="tableSize"
        class="dark:bg-gray-800"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        @selection-change="handleSelectionChange"
        @sorter-change="handleSort"
      >
        <!-- 订单信息列 -->
        <template #order="{ record }">
          <div class="order-info">
            <div class="order-id dark:text-gray-200">
              {{ record.orderNo }}
              <a-tag v-if="record.tags?.includes('vip')" color="gold"
                >VIP</a-tag
              >
              <a-tag v-if="record.tags?.includes('long_stay')" color="blue"
                >长住</a-tag
              >
              <a-tag v-if="record.tags?.includes('group')" color="green"
                >团队</a-tag
              >
              <a-tag v-if="record.tags?.includes('special')" color="orange"
                >特殊要求</a-tag
              >
            </div>
            <div class="order-time dark:text-gray-400">
              {{ record.createTime }}
            </div>
            <div class="order-source dark:text-gray-400">
              <icon-mobile v-if="record.source === 'mobile'" />
              <icon-computer v-if="record.source === 'website'" />
              {{ getSourceText(record.source) }}
            </div>
          </div>
        </template>

        <!-- 客人信息列 -->
        <template #guest="{ record }">
          <div class="guest-info">
            <div class="guest-name">{{ record.guestName }}</div>
            <div class="guest-phone">{{ record.phone }}</div>
            <div class="guest-id" v-if="record.idCard">{{ record.idCard }}</div>
          </div>
        </template>

        <!-- 房间信息列 -->
        <template #room="{ record }">
          <div class="room-info">
            <div class="room-type">{{ record.roomType }}</div>
            <div class="room-number" v-if="record.roomNumber">
              房间号：{{ record.roomNumber }}
            </div>
            <div class="stay-nights">
              共{{ calculateNights(record.checkInDate, record.checkOutDate) }}晚
            </div>
          </div>
        </template>

        <!-- 状态列 -->
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>

        <!-- 操作列 -->
        <template #operation="{ record }">
          <a-space>
            <a-button
              v-if="record.status === 'pending'"
              type="text"
              status="success"
              @click="handleConfirm(record)"
            >
              确认
            </a-button>
            <a-button
              v-if="record.status === 'confirmed'"
              type="text"
              status="primary"
              @click="handleCheckIn(record)"
            >
              办理入住
            </a-button>
            <a-button
              v-if="record.status === 'checked_in'"
              type="text"
              status="warning"
              @click="handleCheckOut(record)"
            >
              办理退房
            </a-button>
            <a-button
              v-if="['pending', 'confirmed'].includes(record.status)"
              type="text"
              status="danger"
              @click="handleCancel(record)"
            >
              取消
            </a-button>
            <a-button type="text" @click="handleViewDetails(record)">
              详情
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 订单详情抽屉 -->
    <a-drawer
      :visible="showDetails"
      :width="600"
      @cancel="showDetails = false"
      unmountOnClose
    >
      <template #title>
        订单详情
        <a-tag
          :color="getStatusColor(selectedOrder?.status)"
          v-if="selectedOrder"
        >
          {{ getStatusText(selectedOrder.status) }}
        </a-tag>
      </template>

      <div v-if="selectedOrder" class="order-details">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="订单号">
            {{ selectedOrder.orderNo }}
          </a-descriptions-item>
          <a-descriptions-item label="下单时间">
            {{ selectedOrder.createTime }}
          </a-descriptions-item>
          <a-descriptions-item label="客人姓名">
            {{ selectedOrder.guestName }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ selectedOrder.phone }}
          </a-descriptions-item>
          <a-descriptions-item label="身份证号">
            {{ selectedOrder.idCard }}
          </a-descriptions-item>
          <a-descriptions-item label="预订来源">
            {{ getSourceText(selectedOrder.source) }}
          </a-descriptions-item>
          <a-descriptions-item label="房型">
            {{ selectedOrder.roomType }}
          </a-descriptions-item>
          <a-descriptions-item label="房间号" v-if="selectedOrder.roomNumber">
            {{ selectedOrder.roomNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="入住时间">
            {{ selectedOrder.checkInDate }}
          </a-descriptions-item>
          <a-descriptions-item label="退房时间">
            {{ selectedOrder.checkOutDate }}
          </a-descriptions-item>
          <a-descriptions-item label="订单金额">
            ¥{{ selectedOrder.amount }}
          </a-descriptions-item>
          <a-descriptions-item label="支付方式">
            {{ getPaymentMethodText(selectedOrder.paymentMethod) }}
          </a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">
            {{ selectedOrder.remarks || "无" }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 订单日志 -->
        <div class="order-logs mt-4">
          <div class="text-lg font-medium mb-2">订单日志</div>
          <a-timeline>
            <a-timeline-item
              v-for="log in selectedOrder.logs"
              :key="log.time"
              :dot-color="getLogColor(log.type)"
            >
              <div class="log-content">
                <span class="log-time">{{ log.time }}</span>
                <span class="log-text">{{ log.content }}</span>
                <span class="log-operator" v-if="log.operator">
                  操作人：{{ log.operator }}
                </span>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end">
          <a-space>
            <a-button @click="showDetails = false">关闭</a-button>
            <a-button type="primary" @click="handlePrint">打印订单</a-button>
          </a-space>
        </div>
      </template>
    </a-drawer>
  </div>
</template>

<script>
import { ref, reactive, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import dayjs from "dayjs";

export default {
  name: "BookingManagement",
  setup() {
    const loading = ref(false);
    const showAdvanced = ref(false);
    const showDetails = ref(false);
    const selectedOrder = ref(null);
    const selectedOrders = ref([]);
    const tableSize = ref("medium");

    // 订单统计数据
    const orderStats = ref([
      {
        title: "今日订单",
        value: 128,
        trend: 12.3,
      },
      {
        title: "待确认",
        value: 23,
        trend: -5.2,
      },
      {
        title: "今日入住",
        value: 45,
        trend: 8.5,
      },
      {
        title: "今日退房",
        value: 38,
        trend: 3.2,
      },
    ]);

    // 搜索表单
    const searchForm = reactive({
      keyword: "",
      status: "",
      dateRange: [],
      roomType: "",
      paymentMethod: "",
      amount: [],
      source: "",
      tags: [],
    });

    // 状态选项
    const statusOptions = [
      { label: "待确认", value: "pending" },
      { label: "已确认", value: "confirmed" },
      { label: "已入住", value: "checked_in" },
      { label: "已退房", value: "checked_out" },
      { label: "已取消", value: "cancelled" },
    ];

    // 房型选项
    const roomTypes = [
      { id: 1, name: "标准单人房" },
      { id: 2, name: "标准双人房" },
      { id: 3, name: "豪华大床房" },
      { id: 4, name: "豪华套房" },
    ];

    // 日期快捷选项
    const dateShortcuts = [
      {
        label: "今日入住",
        value: () => [dayjs(), dayjs()],
      },
      {
        label: "明日入住",
        value: () => [dayjs().add(1, "day"), dayjs().add(1, "day")],
      },
      {
        label: "本周",
        value: () => [dayjs().startOf("week"), dayjs().endOf("week")],
      },
      {
        label: "本月",
        value: () => [dayjs().startOf("month"), dayjs().endOf("month")],
      },
    ];

    // 表格列配置
    const columns = [
      {
        title: "订单信息",
        dataIndex: "order",
        slotName: "order",
        fixed: "left",
        width: 200,
      },
      {
        title: "客人信息",
        dataIndex: "guest",
        slotName: "guest",
        width: 180,
      },
      {
        title: "房间信息",
        dataIndex: "room",
        slotName: "room",
        width: 180,
      },
      {
        title: "入住时间",
        dataIndex: "checkInDate",
        sortable: true,
        width: 120,
      },
      {
        title: "退房时间",
        dataIndex: "checkOutDate",
        sortable: true,
        width: 120,
      },
      {
        title: "状态",
        dataIndex: "status",
        slotName: "status",
        width: 100,
      },
      {
        title: "金额",
        dataIndex: "amount",
        sortable: true,
        width: 100,
      },
      {
        title: "操作",
        slotName: "operation",
        fixed: "right",
        width: 200,
      },
    ];

    // 分页配置
    const pagination = reactive({
      total: 100,
      current: 1,
      pageSize: 10,
      showTotal: true,
      showJumper: true,
      showPageSize: true,
    });

    // 表格选择配置
    const rowSelection = {
      type: "checkbox",
      showCheckedAll: true,
      onlyCurrent: false,
    };

    // 获取状态颜色
    const getStatusColor = (status) => {
      const colors = {
        pending: "orange",
        confirmed: "blue",
        checked_in: "green",
        checked_out: "purple",
        cancelled: "red",
      };
      return colors[status] || "gray";
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        pending: "待确认",
        confirmed: "已确认",
        checked_in: "已入住",
        checked_out: "已退房",
        cancelled: "已取消",
      };
      return texts[status] || status;
    };

    // 获取来源文本
    const getSourceText = (source) => {
      const texts = {
        website: "官网",
        mobile: "手机端",
        ota: "OTA平台",
        walk_in: "门店直订",
      };
      return texts[source] || source;
    };

    // 获取支付方式文本
    const getPaymentMethodText = (method) => {
      const texts = {
        wechat: "微信支付",
        alipay: "支付宝",
        unionpay: "银联支付",
        cash: "现金支付",
      };
      return texts[method] || method;
    };

    // 计算入住天数
    const calculateNights = (checkIn, checkOut) => {
      if (!checkIn || !checkOut) return 0;
      return dayjs(checkOut).diff(dayjs(checkIn), "day");
    };

    // 获取日志颜色
    const getLogColor = (type) => {
      const colors = {
        create: "blue",
        confirm: "green",
        check_in: "orange",
        check_out: "purple",
        cancel: "red",
        modify: "gray",
      };
      return colors[type] || "blue";
    };

    // 处理搜索
    const handleSearch = () => {
      loading.value = true;
      // TODO: 实现搜索逻辑
      setTimeout(() => {
        loading.value = false;
      }, 1000);
    };

    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach((key) => {
        searchForm[key] = Array.isArray(searchForm[key]) ? [] : "";
      });
      handleSearch();
    };

    // 处理刷新
    const handleRefresh = () => {
      loading.value = true;
      // TODO: 实现刷新逻辑
      setTimeout(() => {
        loading.value = false;
      }, 1000);
    };

    // 处理导出
    const handleExport = () => {
      Message.success("开始导出订单数据");
      // TODO: 实现导出逻辑
    };

    // 处理打印
    const handlePrint = () => {
      Message.success("开始打印订单");
      // TODO: 实现打印逻辑
    };

    // 处理确认订单
    const handleConfirm = (record) => {
      Message.success(`订单 ${record.orderNo} 已确认`);
      // TODO: 实现确认逻辑
    };

    // 处理入住
    const handleCheckIn = (record) => {
      Message.success(`订单 ${record.orderNo} 已办理入住`);
      // TODO: 实现入住逻辑
    };

    // 处理退房
    const handleCheckOut = (record) => {
      Message.success(`订单 ${record.orderNo} 已办理退房`);
      // TODO: 实现退房逻辑
    };

    // 处理取消
    const handleCancel = (record) => {
      Message.success(`订单 ${record.orderNo} 已取消`);
      // TODO: 实现取消逻辑
    };

    // 处理查看详情
    const handleViewDetails = (record) => {
      selectedOrder.value = record;
      showDetails.value = true;
    };

    // 处理批量入住
    const handleBatchCheckIn = () => {
      Message.success(
        `已选择 ${selectedOrders.value.length} 个订单进行批量入住`,
      );
      // TODO: 实现批量入住逻辑
    };

    // 处理批量退房
    const handleBatchCheckOut = () => {
      Message.success(
        `已选择 ${selectedOrders.value.length} 个订单进行批量退房`,
      );
      // TODO: 实现批量退房逻辑
    };

    // 处理表格大小切换
    const handleTableSize = (size) => {
      tableSize.value = size;
    };

    // 处理列设置
    const handleColumnSetting = () => {
      Message.info("列设置功能开发中");
      // TODO: 实现列设置逻辑
    };

    return {
      loading,
      showAdvanced,
      showDetails,
      selectedOrder,
      selectedOrders,
      tableSize,
      orderStats,
      searchForm,
      statusOptions,
      roomTypes,
      dateShortcuts,
      columns,
      pagination,
      rowSelection,
      getStatusColor,
      getStatusText,
      getSourceText,
      getPaymentMethodText,
      calculateNights,
      getLogColor,
      handleSearch,
      handleReset,
      handleRefresh,
      handleExport,
      handlePrint,
      handleConfirm,
      handleCheckIn,
      handleCheckOut,
      handleCancel,
      handleViewDetails,
      handleBatchCheckIn,
      handleBatchCheckOut,
      handleTableSize,
      handleColumnSetting,
    };
  },
};
</script>

<style lang="less" scoped>
.orders-page {
  .stat-card {
    .stat-content {
      .stat-title {
        font-size: 14px;
        color: #666;
      }
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        margin: 8px 0;
      }
      .stat-compare {
        font-size: 12px;
        color: #999;
        .trend-up {
          color: #52c41a;
        }
        .trend-down {
          color: #ff4d4f;
        }
      }
    }
  }

  .search-card {
    margin-bottom: 16px;
    .advanced-search {
      padding-top: 16px;
      border-top: 1px dashed var(--color-border);
    }
  }

  .list-card {
    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .order-info {
      .order-id {
        font-weight: bold;
        margin-bottom: 4px;
      }
      .order-time {
        font-size: 12px;
        color: var(--color-text-3);
      }
      .order-source {
        font-size: 12px;
        color: var(--color-text-3);
        margin-top: 4px;
        .source-text {
          margin-left: 4px;
        }
      }
    }

    .guest-info {
      .guest-name {
        font-weight: bold;
      }
      .guest-phone,
      .guest-id {
        font-size: 12px;
        color: var(--color-text-3);
        margin-top: 4px;
      }
    }

    .room-info {
      .room-type {
        font-weight: bold;
      }
      .room-number,
      .stay-nights {
        font-size: 12px;
        color: var(--color-text-3);
        margin-top: 4px;
      }
    }
  }

  .order-details {
    .order-logs {
      .log-content {
        display: flex;
        align-items: center;
        gap: 8px;
        .log-time {
          color: var(--color-text-3);
          font-size: 12px;
        }
        .log-operator {
          color: var(--color-text-3);
          font-size: 12px;
        }
      }
    }
  }

  :deep(.arco-table-th) {
    background-color: var(--color-bg-2);
    &.dark {
      background-color: #1f2937;
      color: #e5e7eb;
    }
  }

  :deep(.arco-table-td) {
    &.dark {
      background-color: #1f2937;
      color: #e5e7eb;
    }
  }
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}
</style>
